<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleTabsClick">
      <el-tab-pane name="first" stretch="true">
        <span slot="label">
          <span class="span-box">
            <span>日常工作</span>
            <el-badge :value="wfCheckCount.workCount" class="item"></el-badge>
          </span>
        </span>
      </el-tab-pane>
      <el-tab-pane name="second">
        <span slot="label">
          <span class="span-box">
            <span>项目工作</span>
            <el-badge :value="wfCheckCount.projectCount" class="item"></el-badge>
          </span>
        </span>
      </el-tab-pane>
      <el-tab-pane name="three">
        <span slot="label">
          <span class="span-box">
            <span>项目阶段工作</span>
            <el-badge :value="wfCheckCount.prijectDistCount" class="item"></el-badge>
          </span>
        </span>
      </el-tab-pane>
    </el-tabs>
    <el-form
            style="margin-top:10px;"
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
      <el-form-item label="申请人" prop="applyUserId">
          <treeselect v-model="queryParams.applyUserId" :options="userTree" :multiple="false"
          :disable-branch-nodes="true" :show-count="false" 
          placeholder="请选择申请人" style="width:200px;"/>
      </el-form-item>

      <el-form-item label="申请时间" prop="applyTime">
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.checkTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择申请时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核状态" prop="state" class="item">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择工作状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in stateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" prop="checkTime">
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.checkTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择审核时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="checkList"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
      height="600"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="checkId" v-if="false" />
      <el-table-column
        label="任务名称"
        align="center"
        prop="workName"
      />
      <el-table-column label="审批内容" align="center" prop="applyContent" />
      <el-table-column label="完成情况" align="center" prop="completion" />
      <el-table-column
        label="申请人"
        align="center"
        prop="applyUserName"
        width="80"
      />
      <el-table-column
        label="申请时间"
        align="center"
        prop="applyTime"
        width="160"
      />
      <el-table-column
        label="审核状态"
        align="center"
        prop="state"
        :formatter="stateFormat"
        width="80"
      />
      <el-table-column
        label="审核时间"
        align="center"
        prop="checkTime"
        width="160"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="160"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleFileUpload(scope.row)"
            >附件</el-button
          >
          <!-- <el-button
            type="text"
            icon="el-icon-check"
            size="mini"
            v-show="checkList[scope.$index].state==2"
            @click="handleCheckOnePerson(scope.row)"
          >提交审核</el-button> -->
          <el-button
            type="text"
            icon="el-icon-check"
            size="mini"
            v-show="
              checkList[scope.$index].state == 0 ||
                checkList[scope.$index].state == 1
            "
            @click="handlePass(scope.row)"
            >通过</el-button
          >
          <el-button
            type="text"
            icon="el-icon-close"
            size="mini"
            v-show="
              checkList[scope.$index].state == 0 ||
                checkList[scope.$index].state == 1
            "
            @click="handleRefuse(scope.row)"
            >拒绝</el-button
          >
          <el-button
            type="text"
            icon="el-icon-circle-close"
            size="mini"
            v-show="
              checkList[scope.$index].state == 0 ||
                checkList[scope.$index].state == 1
            "
            @click="handleCallBack(scope.row)"
            >打回</el-button
          >
          <el-button
            type="text"
            icon="el-icon-notebook-1"
            size="mini"
            @click="handleLog(scope.row)"
            >查看日志</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      style=" margin-bottom: 30px;"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    

    <!-- 查看日志 -->
    <el-dialog
      title="查看日志"
      :visible.sync="logVisible"
      width="800px"
      append-to-body
    >
      <el-table :data="logData">
        <el-table-column
          property="createTime"
          label="审核时间"
          width="150"
        ></el-table-column>
        <el-table-column
          property="personnelName"
          label="操作人姓名"
          width="200"
        ></el-table-column>
        <el-table-column
          property="state"
          label="审核状态"
          width="200"
          :formatter="logStateFormat"
        ></el-table-column>
        <el-table-column
          property="content"
          label="备注"
          width="200"
        ></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 上传文件 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      :close-on-click-modal="false"
      width="800px"
      append-to-body
    >
      <el-tabs v-model="upload.activeName">
        <el-tab-pane
          id="fileUpload"
          label="上传"
          name="first"
          v-hasPermi="['myjob:waitwork:uploadFile']"
        >
          <el-upload
            ref="upload"
            :headers="upload.headers"
            :limit="1"
            :data="upload.data"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadFile"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
          </el-upload>
          <el-button
            type="primary"
            @click="submitFileForm"
            style="display:block;margin:0 auto;marginTop:1em"
            >上 传</el-button
          >
        </el-tab-pane>
        <el-tab-pane label="附件查看" name="second">
          <el-row :gutter="10" class="mb8"> </el-row>
          <el-table
            v-loading="loading"
            :data="upload.fileLists"
            border
            @selection-change="handleSelectionFileChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="文件ID"
              align="center"
              prop="id"
              v-if="false"
            />
            <el-table-column
              label="文件URL"
              align="center"
              prop="url"
              v-if="false"
            />
            <el-table-column label="文件名称" align="center" prop="name" />
            <el-table-column
              label="文件类型"
              align="center"
              prop="type"
              :formatter="stateFileTypeFormat"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  v-hasPermi="['myjob:waitwork:downFile']"
                  @click="handleFileDownload(scope.row)"
                  >下载</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleFileDelete(scope.row)"
                  v-hasPermi="['myjob:waitwork:deleFile']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="upload.total > 0"
            :total="upload.total"
            :page.sync="upload.queryParams.pageNum"
            :limit.sync="upload.queryParams.pageSize"
            @pagination="getList"
          />
        </el-tab-pane>
        <el-tab-pane label="相关附件" name="third">
          <el-row :gutter="10" class="mb8">
            <el-table
              v-loading="loading"
              :data="upload.relevantFile"
              border
              @selection-change="handleSelectionFileChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column
                label="文件ID"
                align="center"
                prop="id"
                v-if="false"
              />
              <el-table-column
                label="文件URL"
                align="center"
                prop="url"
                v-if="false"
              />
              <el-table-column label="文件名称" align="center" prop="name" />
              <el-table-column
                label="文件类型"
                align="center"
                prop="type"
                :formatter="stateFileTypeFormat"
              />
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    v-hasPermi="['myjob:waitwork:downFile']"
                    @click="handleFileDownload(scope.row)"
                    >下载</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleFileDelete(scope.row)"
                    v-hasPermi="['myjob:waitwork:deleFile']"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改审批记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级ID" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入上级ID" />
        </el-form-item>
        <el-form-item label="申请ID" prop="applyId">
          <el-input v-model="form.applyId" placeholder="请输入申请ID" />
        </el-form-item>
        <el-form-item label="审核人ID" prop="checkUserId">
          <el-input v-model="form.checkUserId" placeholder="请输入审核人ID" />
        </el-form-item>
        <el-form-item label="审核状态" prop="state">
          <el-input v-model="form.state" placeholder="请输入审核状态" />
        </el-form-item>
        <el-form-item label="审核时间" prop="checkTime">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.checkTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择审核时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCheck,
  getCheck,
  delCheck,
  addCheck,
  updateCheck,
  exportCheck,
  getCheckCount
} from "@/api/workflow/check";
import {
  logList,
  FileAllList,
  flowList,
  ReFlowData
} from "@/api/workflow/apply";
import {getUserTree} from "@/api/trialproduce/car";
import { getToken } from "@/utils/auth";
import { selectFiles, deleteFiles } from "@/api/work/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Check",
  components: { Treeselect },
  data() {
    return {
      upload: {
        title: null,
        open: false,
        // 上传标签页
        activeName: "first",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 是否禁用上传
        isUploading: false,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/work/process/user/upload",
        //路径
        baseURL: process.env.VUE_APP_BASE_API,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        data: {
          tableId: null
        },
        //总数
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          applyType: 0
        },
        relevantFile: [
          {
            id: "",
            url: "",
            name: "",
            type: ""
          }
        ],
        fileLists: [
          {
            id: "",
            url: "",
            name: "",
            type: ""
          }
        ]
      },
      //用户数结构
      userTree:[],
      flowData: {},
      checkId: "",
      state: "",
      applyId: "",
      title: "",
      flowForm: {},
      // 日志
      logData: [],
      logVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批记录表格数据
      checkList: [],
      // 申请类型字典
      applyTypeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 审核状态字典
      stateOptions: [],
      //日志状态字典
      logStateOption: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applyId: null,
        checkUserId: null,
        state: null,
        checkTime: null,
        applyUserId: null
      },
      // 表单参数
      form: {},
      //文件类型
      textFileTypeOptions: [],
      // 表单校验
      rules: {},
      activeName: 'first',
      wfCheckCount: {
        workCount:0,
        projectCount:0,
        prijectDistCount:0
      }
    };
  },
  created() {
    this.getCheckCount();
    this.getList();
    this.handleUserTree();
    this.getDicts("wf_check_state").then(response => {
      this.stateOptions = response.data;
    });
    this.getDicts("wf_apply_type").then(response => {
      this.applyTypeOptions = response.data;
    });
    this.getDicts("wf_check_state").then(response => {
      this.logStateOption = response.data;
      this.logStateOption.forEach(item => {
        if (item.dictValue == 1) {
          item.dictLabel = "已申请";
        }
      });
    });
    this.getDicts("sys_file_type").then(response => {
      this.textFileTypeOptions = response.data;
    });
  },
  methods: {
    //用户树
    handleUserTree(){
      getUserTree().then(response => {
        this.userTree = response.data;
      });
    },
    // 文件类型翻译
    stateFileTypeFormat(row, column) {
      return this.selectDictLabel(this.textFileTypeOptions, row.type);
    },
    // 查看日志
    handleLog(row) {
      var applyId = row.applyId;
      var query = {
        applyId: applyId
      };
      this.logVisible = true;
      logList(query).then(response => {
        console.log("查看日志", response);
        this.logData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 申请类型字典翻译
    applyTypeFormat(row, column) {
      return this.selectDictLabel(this.applyTypeOptions, row.applyType);
    },
    // 通过
    handlePass(row) {
      this.checkId = row.checkId;
      this.state = 5;
      this.applyId = row.applyId;
      this.$prompt("请输入审核意见", "审核意见", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
        // inputPattern: /\S/,
        // inputErrorMessage: '请输入审核意见'
      })
        .then(({ value }) => {
          let data = {
            content: value,
            checkId: this.checkId,
            state: this.state,
            applyId: this.applyId
          };
          flowList(data).then(response => {
            if (response.code === 200) {
              this.$message({
                type: "success",
                message: "审核通过!"
              });
              this.getList();
              this.getCheckCount();
            }
          });
          
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消"
          });
        });
        
    },
    // 审核拒绝
    handleRefuse(row) {
      this.checkId = row.checkId;
      this.state = 3;
      this.applyId = row.applyId;
      this.$prompt("请输入审核意见", "审核意见", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "请输入审核意见"
      })
        .then(({ value }) => {
          let data = {
            content: value,
            checkId: this.checkId,
            state: this.state,
            applyId: this.applyId
          };

          flowList(data).then(response => {
            if (response.code === 200) {
              this.$message({
                type: "success",
                message: "你的审核意见是: " + value
              });
              this.getList();
              this.getCheckCount();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消"
          });
        });
        
    },
    // 审核打回
    handleCallBack(row) {
      this.checkId = row.checkId;
      this.state = 2;
      this.applyId = row.applyId;
      this.$prompt("请输入审核意见", "审核意见", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "请输入审核意见"
      })
        .then(({ value }) => {
          let data = {
            content: value,
            checkId: this.checkId,
            state: this.state,
            applyId: this.applyId
          };
          flowList(data).then(response => {
            if (response.code === 200) {
              this.$message({
                type: "success",
                message: "你的审核意见是: " + value
              });
              this.getList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消"
          });
        });
    },

    /** 查询审批记录列表 */
    getList() {
      this.loading = true;
      listCheck(this.queryParams).then(response => {
        this.checkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 审核状态字典翻译
    stateFormat(row, column) {
      return this.selectDictLabel(this.stateOptions, row.state);
    },
    // 日志字典查看
    logStateFormat(row, column) {
      return this.selectDictLabel(this.logStateOption, row.state);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        checkId: null,
        parentId: null,
        applyId: null,
        checkUserId: null,
        state: null,
        checkTime: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getCheckCount();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.checkId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加审批记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const checkId = row.checkId || this.ids;
      getCheck(checkId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改审批记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.checkId != null) {
            updateCheck(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCheck(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const checkIds = row.checkId || this.ids;
      this.$confirm(
        '是否确认删除审批记录编号为"' + checkIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delCheck(checkIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有审批记录数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportCheck(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    },
    /** 附件上传按钮操作 */
    handleFileUpload(row) {
      const itemId = row.tableId;
      this.upload.title = "上传附件";
      this.upload.open = true;
      this.upload.data.tableId = itemId;
      this.getFileList();
    },
    // 附件上传中处理
    handleFileUploadFile(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 附件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = true;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "上传结果", { dangerouslyUseHTMLString: true });
      this.getFileList();
      this.getList();
    },
    // 附件提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //附件列表
    handleSelectionFileChange(selection) {
      this.id = selection.map(item => item.id);
      this.uri = selection.map(item => item.uri);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查询附件列表 */
    getFileList() {
      this.loading = true;
      FileAllList(this.upload.data.tableId).then(response => {
        this.upload.fileLists = response.data.itemFile;
        this.upload.relevantFile = response.data.relevantFile;
        // this.upload.total = response.total;
      });
      this.loading = false;
    },
    // 删除文件操作
    handleFileDelete(row) {
      const id = row.id || this.id;
      this.$confirm('是否确认删除任务分配编号为"' + id + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return deleteFiles(id);
        })
        .then(() => {
          this.getFileList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    // 下载文件
    handleFileDownload(row) {
      const id = row.id || this.id;
      const url = row.uri || this.uri;
      window.location.href = this.upload.baseURL + url;
    },
    //菜单切换
    handleTabsClick(tab, event){
      if(tab.name == "first"){
        this.queryParams.applyType = 0;
      }else if(tab.name == "second"){
        this.queryParams.applyType = 1;
      }else{
        this.queryParams.applyType = 2;
      }
      this.getList();
      console.log(tab.name, event);
    },
    //统计
    getCheckCount(){
      getCheckCount().then(response => {
        console.log(response);
        this.wfCheckCount = response.data;
      });
    }
  
  }
};
</script>
<style>
.el-upload-list__item-name {
  font-size: 16px;
 
}
#fileUpload .el-upload-dragger {
  display: block;
  margin: 0 auto;
  margin-top: 1em;
  width: 760px;
  height: 180px;
}
.span-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.span-box .btn-bell-badge {
  height: 18px;
  padding: 0 5px;
  margin-left: 5px;
  line-height: 18px;
  border-radius: 15px;
  background: #f56c6c;
}
.span-box .btn-bell-badge .num {
  display: block;
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: #fff;
}
</style>
